const crypto = require('crypto');

let server = function (app, db) {

    //?Cookie查询
    const View_Cookie = function (request, calka) {
        db.query('select * from admin_login where AdminCookie=\'' + request.cookies.DOM_Cookie_admin + '\'', function (err, data) {
            calka(err, data)
        })
    }

    //?login，登录接口</login>
    app.post('/login_admin', function (request, response) {
        if (request.body.UserPassword != null && request.body.UserID != null) {
            // console.log(request.body.UserID);
            db.query('select AdminPassword from admin where AdminID=?', [request.body.UserID], function (err, data) {
                if (err) {
                    console.error(err);
                    response.send({ "code": -1, "msg": "error" })
                }
                else {
                    console.log(data);
                    if (data[0]) {
                        if (data[0]['AdminPassword'] == request.body.UserPassword) {
                            const md5 = crypto.createHash('md5');//?生成md5实例（一次性）
                            let time__ = new Date().getTime();//?时间戳
                            const cookie = md5.update(String(parseInt(time__ * 3000))).digest('hex');//?md5加密
                            db.query('update admin_login set AdminCookie=\'' + cookie + '\' where AdminID=' + request.body.UserID, function (err, data) {
                                response.cookie('DOM_Cookie_admin', cookie, { maxAge: 60 * 60 * 1000 });
                                response.send({ "code": 0, "msg": "登录成功" })
                            })
                        }
                        else response.send({ "code": -1, "msg": "密码错误" })
                    } else response.send({ "code": -1, "msg": "账号不存在" })
                }
            })
        } else response.send({ "code": -1, "msg": "error" })
    })

    //?管理员信息
    app.post('/data_admin', function (request, response) {
        View_Cookie(request, function (err, data) {
            if (data[0]) {
                db.query('select * from admin where AdminID=' + data[0].AdminID, function (err, data1) {
                    response.send({ "code": 0, "data": data1 })
                })
            } else {
                response.send({ "code": -1, "data": "未登录" })
            }
        })
    })

    //?退出登录
    app.post('/admin/Exit', function (request, response) {
        response.clearCookie('DOM_Cookie_admin')
        response.end()
    })
}
module.exports = server
